import Tkinter as tk
import Widgets
from Base import *

## this is a handler (controller) connecting the widget with the
#  model(s) and vice versa.
class ListboxHandler(BaseHandler):
    def __init__(self, factory, widget):
        BaseHandler.__init__(self, factory, widget)
        self.widget.bind('<ButtonRelease-1>', self.onButtonRelease1)
        self.widget.bind('<KeyRelease>', self.onKeyRelease)
        self.widget.bind('<Double-Button-1>', self.onDoubleClick1)

    def initialize(self, wid, attributes):
        self.wid = wid
        self.factory.registerHandler(wid, self)

    ## indicates that a user has selected an entry
    def selected(self, event):
        selection = map(int, self.widget.curselection())
        if len(selection) > 0:
            entry = self.widget.get(selection[0])
            #print "Listbox entry '%s' has been selected" % (entry)

            for model in self.models:
                model.updateValue(self.wid, entry, "changed")

    ## trying to select all or a certain row
    def select(self, row = -1, column = -1):
        self.widget.selection_clear(0, tk.END)
        if row >= 0:
            self.widget.selection_set(row, row)
            self.widget.see(row)

    ## indicates that a user has deleted an entry
    def deleted(self, event):
        selection = map(int, self.widget.curselection())
        if len(selection) > 0:
            entry = self.widget.get(selection[0])
            self.widget.delete(selection[0])
            for model in self.models:
                model.updateValue(self.wid, entry, "deleted")

    def onButtonRelease1(self, event):
        self.selected(event)
        self.widget.focus()

    def onKeyRelease(self, event):
        if event.keysym in ["Up", "Down", "space"]:
            self.selected(event)
        elif event.keysym in ["Delete"]:
            self.deleted(event)

    def onDoubleClick1(self, event):
        self.selected(event)

    def addValue(self, value):
        self.widget.add(value)

    ## trying to get value of given row
    def getValue(self, row=-1, column=-1):
        if row >= 0 and row < self.widget.size():
            return self.widget.entries()[row]
        return None

    def removeValue(self, value):
        size  = self.widget.size()
        index = 0

        while index < size:
            entry = self.widget.get(index, index)
            if type(entry) == type(""):
                if entry == value:
                    self.widget.delete(index, index)
                    return
            elif entry[0] == value:
                self.widget.delete(index, index)
                return
            index += 1

        print "lbh - failed to remove value %s" % (value)

    ## removing content
    #  @param  row    [in] ignored
    #  @param  column [in] ignored
    #  @return none.
    def clear(self, row = -1, column = -1):
        self.widget.clear()

